package com.yuwj.chinaa.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.yuwj.chinaa.R;
import com.yuwj.chinaa.base.BaseActivity;
import com.yuwj.chinaa.base.ConstantParam;
import com.yuwj.chinaa.entity.EntityBurseCoinNumber;
import com.yuwj.chinaa.entity.EntityOrderWithTrade;
import com.yuwj.chinaa.entity.EntityUser;
import com.yuwj.chinaa.presenter.IPresenter;
import com.yuwj.chinaa.presenter.presenterImpl.PresenterImpl;
import com.yuwj.chinaa.util.MathUtil;
import com.yuwj.chinaa.util.SharedpreferenceUtil;
import com.yuwj.chinaa.util.ToastUtil;

import org.json.JSONException;
import org.json.JSONObject;

import butterknife.BindView;
import butterknife.OnClick;
import de.hdodenhof.circleimageview.CircleImageView;

//求购，出售列表详情
public class TradeListDetailActivity extends BaseActivity {


    int tradeType;//ConstantParam.TRANSACTION_TYPE_WITH_BUY -买入
    EntityOrderWithTrade entityOrder;//求购或出售详情
    AlertDialog alertDialogWithPayPasswordInput;
    IPresenter presenter;
    EntityBurseCoinNumber entityBurseCoinNumber;

    @BindView(R.id.iv_back)
    ImageButton ivBack;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.civ_user_photo)
    CircleImageView civUserPhoto;
    @BindView(R.id.tv_user_name)
    TextView tvUserName;
    @BindView(R.id.tv_chengj_count)
    TextView tvChengjCount;
    @BindView(R.id.tv_chengj_lv)
    TextView tvChengjLv;
    @BindView(R.id.tv_gte_count)
    TextView tvGteCount;
    @BindView(R.id.tv_price)
    TextView tvPrice;
    @BindView(R.id.tv_xiane)
    TextView tvXiane;
    @BindView(R.id.tv_shouxf)
    TextView tvShouxf;
    @BindView(R.id.tv_cny)
    TextView tvCny;
    @BindView(R.id.tv_trade_type)
    TextView tvTradeType;
    @BindView(R.id.tv_sell_all)
    TextView tvSellAll;
    @BindView(R.id.et_gte_count)
    EditText etGteCount;
    @BindView(R.id.tv_cny_count)
    TextView tvCnyCount;
    @BindView(R.id.ll_input_container)
    LinearLayout llInputContainer;
    @BindView(R.id.ll_trade_confirm)
    LinearLayout llTradeConfirm;
    @BindView(R.id.ll_trade_cancel)
    LinearLayout llTradeCancel;
    @BindView(R.id.tv_trade_type_text)
    TextView tvTradeTypeText;

    @Override
    public int setCustomContentViewResourceId() {
        return R.layout.activity_trade_list_detail;
    }

    public static Intent createIntent(Context context, EntityOrderWithTrade order, int tradeType) {
        Intent intent = new Intent(context, TradeListDetailActivity.class);
        intent.putExtra("tradetype", tradeType);
        intent.putExtra("entityOrder", order);
        return intent;
    }


    @Override
    public void initParam() {
        tradeType = getIntent().getIntExtra("tradetype", ConstantParam.TRANSACTION_TYPE_WITH_BUY);
        entityOrder = (EntityOrderWithTrade) getIntent().getSerializableExtra("entityOrder");
        presenter = new PresenterImpl(this);
    }

    @Override
    public void initView() {
        updateDeatilViewByTradeType();
        tvXiane.setText(entityOrder.getChinaANumber() + "");
        etGteCount.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                float price = SharedpreferenceUtil.getInstance().getTodayPrice(context);
                String count = etGteCount.getText().toString().trim();
                if (TextUtils.isEmpty(count)) {
                    tvCnyCount.setText("");
                } else {
                    tvCnyCount.setText(MathUtil.multiply(price + "", count + "") + "");
                }
            }
        });

        //如果订单的用户就是自己登陆用户，可以显示取消挂单按钮
        if (!TextUtils.isEmpty(entityOrder.getUserId()) && entityOrder.getUserId().equals(entityUser.getID())) {
            llTradeCancel.setVisibility(View.VISIBLE);
            llTradeConfirm.setVisibility(View.GONE);
        } else {
            llTradeCancel.setVisibility(View.GONE);
            llTradeConfirm.setVisibility(View.VISIBLE);
        }
    }


    @Override
    public void initOperator() {

        JSONObject paramWithgetUserBurseCoinNumberList = new JSONObject();
        presenter.getUserBurseCoinNumberList(paramWithgetUserBurseCoinNumberList.toString());
    }


    //展示输入支付密码对话框
    public void showInputPayPasswordDialog() {
        if (alertDialogWithPayPasswordInput == null) {
            alertDialogWithPayPasswordInput = new AlertDialog.Builder(context).create();
            View contentView = View.inflate(context, R.layout.content_input_pay_password, null);
            alertDialogWithPayPasswordInput.setView(contentView);
            LinearLayout llDismiss = (LinearLayout) contentView.findViewById(R.id.ll_dismiss);
            final EditText etpassword = (EditText) contentView.findViewById(R.id.et_pay_password);
            TextView tvNext = (TextView) contentView.findViewById(R.id.tv_buy);
            View.OnClickListener onClickListener = new View.OnClickListener() {

                @Override
                public void onClick(View view) {
                    switch (view.getId()) {
                        case R.id.ll_dismiss:
                            alertDialogWithPayPasswordInput.dismiss();
                            break;
                        case R.id.tv_buy:

                            String number = etGteCount.getText().toString();
                            float price = SharedpreferenceUtil.getInstance().getTodayPrice(context);
                            String amount = "";
                            if (!TextUtils.isEmpty(number)) {
                                amount = (Double.parseDouble(number) * price) + "";
                            }
                            if (TextUtils.isEmpty(etpassword.getText().toString().trim())) {
                                ToastUtil.getInstance().shortLength(context, "请输入支付密码");
                                return;
                            }

                            switch (tradeType) {
                                case ConstantParam.TRANSACTION_TYPE_WITH_BUY:
                                    JSONObject paramWithSell = new JSONObject();
                                    try {
                                        paramWithSell.put("bicount", entityOrder.getChinaANumber() + "");
                                        paramWithSell.put("pricermb", entityOrder.getPriceRMB() + "");
                                        paramWithSell.put("limitmix", entityOrder.getLimitMix() + "");
                                        paramWithSell.put("limitmax", entityOrder.getLimitMax() + "");
                                        paramWithSell.put("ordertype", entityOrder.getTransactionType() == ConstantParam.TRANSACTION_TYPE_WITH_BUY ? "0" : "1");
                                        paramWithSell.put("paypwd", etpassword.getText().toString().trim() + "");
                                    } catch (JSONException e) {
                                        e.printStackTrace();
                                    }
                                    presenter.gteBuyOrSell(paramWithSell.toString());
                                    break;
                                case ConstantParam.TRANSACTION_TYPE_WITH_SELL:
                                    JSONObject paramWithBuy = new JSONObject();
                                    try {
                                        paramWithBuy.put("orderId", entityOrder.getID() + "");
                                        paramWithBuy.put("biCount", entityOrder.getChinaANumber() + "");
                                        paramWithBuy.put("biPrice", entityOrder.getPriceRMB() + "");
                                        paramWithBuy.put("paypwd", etpassword.getText().toString().trim() + "");
                                    } catch (JSONException e) {
                                        e.printStackTrace();
                                    }
                                    presenter.userBuyTrade(paramWithBuy.toString());
                                    break;
                            }
                            alertDialogWithPayPasswordInput.dismiss();
                            break;
                    }
                }
            };
            llDismiss.setOnClickListener(onClickListener);
            tvNext.setOnClickListener(onClickListener);
            alertDialogWithPayPasswordInput.setCancelable(false);
            alertDialogWithPayPasswordInput.setCanceledOnTouchOutside(false);
        }
        alertDialogWithPayPasswordInput.show();
    }

    public void updateDeatilViewByTradeType() {
        if (tradeType == ConstantParam.TRANSACTION_TYPE_WITH_BUY) {
            tvTitle.setText("求购详情");
            llInputContainer.setVisibility(View.VISIBLE);
            tvTradeTypeText.setText("立即卖出");
        } else {
            tvTitle.setText("出售详情");
            llInputContainer.setVisibility(View.GONE);
            tvTradeTypeText.setText("立即买入");
        }

        Glide.with(context).load(entityOrder.getUserName()).error(R.mipmap.ic_asset_user_photo).into(civUserPhoto);
        tvUserName.setText(entityOrder.getUserName());
        tvChengjCount.setText(entityOrder.getTurnoverCount() + "");
        tvChengjLv.setText(entityOrder.getTurnoverRate() + "%");

        tvGteCount.setText(entityOrder.getChinaANumber() + " china-A");
        tvPrice.setText(entityOrder.getPriceRMB() + " CNY");
        tvXiane.setText(entityOrder.getLimitMax() + " china-A");
        tvCny.setText(entityOrder.getPriceCountRMB() + " CNY");
        tvShouxf.setText(entityOrder.getServiceCharge() + "%");
    }

    @Override
    public void gteBuyOrSellSuccess(String data) {
        super.gteBuyOrSellSuccess(data);
        ToastUtil.getInstance().shortLength(context, "挂单成功");
        finish();
    }

    @Override
    public void gteBuyOrSellFail(Exception e) {
        super.gteBuyOrSellFail(e);
        ToastUtil.getInstance().shortLength(context, e.getMessage());
    }

    @Override
    public void onUserBuyTradeSuccess() {
        super.onUserBuyTradeSuccess();
        ToastUtil.getInstance().shortLength(context, "买入成功");
        finish();

    }

    @Override
    public void onUserBuyTradeFail(Exception e) {
        super.onUserBuyTradeFail(e);
        ToastUtil.getInstance().shortLength(context, e.getMessage());

    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public void onCancelUnTradeTransactionOrderSuccess() {
        super.onCancelUnTradeTransactionOrderSuccess();
        ToastUtil.getInstance().shortLength(context, "取消交易成功");
        finish();
    }

    @Override
    public void onCancelUnTradeTransactionOrderFail(Exception e) {
        super.onCancelUnTradeTransactionOrderFail(e);
        ToastUtil.getInstance().shortLength(context, e.getMessage());

    }

    @OnClick({R.id.iv_back, R.id.tv_sell_all, R.id.ll_trade_confirm, R.id.ll_trade_cancel})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.tv_sell_all:

                double avliable = 0;
                if (entityBurseCoinNumber != null) {
                    avliable = entityBurseCoinNumber.getAvailableBurseCoinNumber();
                }
                double need = entityOrder.getChinaANumber();
                if (avliable > need) {
                    etGteCount.setText(need + "");
                } else {
                    etGteCount.setText(avliable + "");
                }
                etGteCount.setSelection(etGteCount.getText().toString().length());
                break;
            case R.id.ll_trade_cancel:

                JSONObject param = new JSONObject();
                try {
                    param.put("orderid", entityOrder.getID() + "");
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                presenter.cancelUntradeOrder(param.toString());
                break;
            case R.id.ll_trade_confirm:

                if (tradeType == ConstantParam.TRANSACTION_TYPE_WITH_BUY) {
                    String number = etGteCount.getText().toString();
                    if (TextUtils.isEmpty(number)) {
                        ToastUtil.getInstance().shortLength(context, "请输入卖出数量");
                        return;
                    }
                    float price = SharedpreferenceUtil.getInstance().getTodayPrice(context);
                    String amount = (Double.parseDouble(number) * price) + "";
                    if (Double.parseDouble(number) < 1) {
                        ToastUtil.getInstance().shortLength(context, "请输入>1的chinaA数量");
                        return;
                    }
                    EntityUser entityUser = SharedpreferenceUtil.getInstance().getUserInfo(context);
                    if (entityUser.getIsIdentification() != ConstantParam.GENERAL_AUTH_WITH_SUCCESS) {
                        ToastUtil.getInstance().shortLength(context, "请先实名认证");
                        return;
                    }
                    showInputPayPasswordDialog();
                } else {
                    showInputPayPasswordDialog();
                }
                break;
        }
    }

    @Override
    public void onGetUserBurseCoinNumberListSuccess(EntityBurseCoinNumber entityBurseCoinNumber) {
        super.onGetUserBurseCoinNumberListSuccess(entityBurseCoinNumber);
        if (entityBurseCoinNumber != null) {
            this.entityBurseCoinNumber = entityBurseCoinNumber;
        }
    }

    @Override
    public void onGetUserBurseCoinNumberListFail(Exception e) {
        super.onGetUserBurseCoinNumberListFail(e);
        ToastUtil.getInstance().shortLength(context, "" + e.getMessage());
    }
}
